# UART Tx/Rx demo
import re
import tkinter as tk
from tkinter import ttk
import serial
import threading
from math   import *

# A simple Information Window
class InformWindow:
    def __init__(self, informStr):
        self.window = tk.Tk()
        self.window.title("Information")
        self.window.geometry("220x60")
        label = tk.Label(self.window, text=informStr)
        buttonOK = tk.Button(self.window, text="OK", command=self.processButtonOK)
        label.pack(side=tk.TOP)
        buttonOK.pack(side=tk.BOTTOM)
        self.window.mainloop()

    def processButtonOK(self):
        self.window.destroy()


class mainGUI:
    def __init__(self):
        # tempt=[0,0,0,0,0]*10
        window = tk.Tk()
        window.title("温控 Demo")
        self.uartState = False  # is uart open or not

        # a frame contains COM's information, and start/stop button
        frame_COMinf = tk.Frame(window)
        frame_COMinf.grid(row=1, column=1)

        labelCOM = tk.Label(frame_COMinf, text="COMx: ")
        self.COM = tk.StringVar(value="COM3")
        ertryCOM = tk.Entry(frame_COMinf, textvariable=self.COM)
        labelCOM.grid(row=1, column=1, padx=5, pady=3)
        ertryCOM.grid(row=1, column=2, padx=5, pady=3)

        labelBaudrate = tk.Label(frame_COMinf, text="Baudrate: ")
        self.Baudrate = tk.IntVar(value=115200)
        ertryBaudrate = tk.Entry(frame_COMinf, textvariable=self.Baudrate)
        labelBaudrate.grid(row=1, column=3, padx=5, pady=3)
        ertryBaudrate.grid(row=1, column=4, padx=5, pady=3)

        labelParity = tk.Label(frame_COMinf, text="Parity: ")
        self.Parity = tk.StringVar(value="NONE")
        comboParity = ttk.Combobox(frame_COMinf, width=17, textvariable=self.Parity)
        comboParity["values"] = ("NONE", "ODD", "EVEN", "MARK", "SPACE")
        comboParity["state"] = "readonly"
        labelParity.grid(row=2, column=1, padx=5, pady=3)
        comboParity.grid(row=2, column=2, padx=5, pady=3)

        labelStopbits = tk.Label(frame_COMinf, text="Stopbits: ")
        self.Stopbits = tk.StringVar(value="1")
        comboStopbits = ttk.Combobox(frame_COMinf, width=17, textvariable=self.Stopbits)
        comboStopbits["values"] = ("1", "1.5", "2")
        comboStopbits["state"] = "readonly"
        labelStopbits.grid(row=2, column=3, padx=5, pady=3)
        comboStopbits.grid(row=2, column=4, padx=5, pady=3)

        self.buttonSS = tk.Button(frame_COMinf, text="开始通信", command=self.processButtonSS)
        self.buttonSS.grid(row=3, column=4, padx=5, pady=3, sticky=tk.E)

        # serial object
        self.ser = serial.Serial()
        # serial read threading
        self.ReadUARTThread = threading.Thread(target=self.ReadUART)
        self.ReadUARTThread.start()

        frameRecv = tk.Frame(window)
        frameRecv.grid(row=2, column=1)
        labelOutText = tk.Label(frameRecv, text="历史温度:")
        labelOutText.grid(row=1, column=1, padx=3, pady=2, sticky=tk.W)
        frameRecvSon = tk.Frame(frameRecv)
        frameRecvSon.grid(row=2, column=1)
        scrollbarRecv = tk.Scrollbar(frameRecvSon)
        scrollbarRecv.pack(side=tk.RIGHT, fill=tk.Y)
        self.OutputText = tk.Text(frameRecvSon, wrap=tk.WORD, width=60, height=10, yscrollcommand=scrollbarRecv.set)
        self.OutputText.pack()

        frameRecv = tk.Frame(window)
        frameRecv.grid(row=3, column=1)
        labelOutText = tk.Label(frameRecv, text="当前温度:")
        labelOutText.grid(row=1, column=1, padx=3, pady=2, sticky=tk.W)
        frameRecvSon = tk.Frame(frameRecv)
        frameRecvSon.grid(row=2, column=1)
        scrollbarRecv = tk.Scrollbar(frameRecvSon)
        scrollbarRecv.pack(side=tk.RIGHT, fill=tk.Y)
        self.OutputText1 = tk.Text(frameRecvSon, wrap=tk.WORD, width=60, height=5, yscrollcommand=scrollbarRecv.set)
        self.OutputText1.pack()



        self.canvas = tk.Canvas(window,width=400, height=200, bg="white")
        self.canvas.grid(row=4, column=1)
        # self.canvas.create_line(0, 100, 200, 200, fill='red',tags='o')
        self.canvas.create_line(1, 1, 400, 1, dash=(4, 4))  # x轴
        self.canvas.create_line(1, 1, 1, 400, dash=(4, 4))  # y轴
        # self.canvas.delete('o')
        # self.canvas.pack()





        frameTrans = tk.Frame(window)
        frameTrans.grid(row=5, column=1)
        labelInText = tk.Label(frameTrans, text="目标温度:")
        labelInText.grid(row=1, column=1, padx=3, pady=2, sticky=tk.W)
        frameTransSon = tk.Frame(frameTrans)
        frameTransSon.grid(row=2, column=1)
        scrollbarTrans = tk.Scrollbar(frameTransSon)
        scrollbarTrans.pack(side=tk.RIGHT, fill=tk.Y)
        self.InputText = tk.Text(frameTransSon, wrap=tk.WORD, width=60, height=5, yscrollcommand=scrollbarTrans.set)
        self.InputText.pack()
        self.buttonSend = tk.Button(frameTrans, text="发送", command=self.processButtonSend)
        self.buttonSend.grid(row=3, column=1, padx=5, pady=3, sticky=tk.E)

        window.mainloop()

    def processButtonSS(self):
        # print(self.Parity.get())
        if (self.uartState):
            self.ser.close()
            self.buttonSS["text"] = "开始通信"
            self.uartState = False
        else:
            # restart serial port
            self.ser.port = self.COM.get()
            self.ser.baudrate = self.Baudrate.get()

            strParity = self.Parity.get()
            if (strParity == "NONE"):
                self.ser.parity = serial.PARITY_NONE
            elif (strParity == "ODD"):
                self.ser.parity = serial.PARITY_ODD
            elif (strParity == "EVEN"):
                self.ser.parity = serial.PARITY_EVEN
            elif (strParity == "MARK"):
                self.ser.parity = serial.PARITY_MARK
            elif (strParity == "SPACE"):
                self.ser.parity = serial.PARITY_SPACE

            strStopbits = self.Stopbits.get()
            if (strStopbits == "1"):
                self.ser.stopbits = serial.STOPBITS_ONE
            elif (strStopbits == "1.5"):
                self.ser.stopbits = serial.STOPBITS_ONE_POINT_FIVE
            elif (strStopbits == "2"):
                self.ser.stopbits = serial.STOPBITS_TWO

            try:
                self.ser.open()
            except:
                infromStr = "Can't open " + self.ser.port
                InformWindow(infromStr)

            if (self.ser.isOpen()):  # open success
                self.buttonSS["text"] = "Stop"
                self.uartState = True

    def processButtonSend(self):
        if (self.uartState):
            strToSend = self.InputText.get(1.0, tk.END)
            bytesToSend = strToSend[0:-1].encode(encoding='ascii')
            self.ser.write(bytesToSend)
            print(bytesToSend)
        else:
            infromStr = "Not In Connect!"
            InformWindow(infromStr)

    def ReadUART(self):
        # print("Threading...")
        all = ''
        lasttemp = 100
        lastpwm = 200
        i=0
        tempt=[0,0,0,0,0]*20
        while True:
            if (self.uartState):
                try:
                    ch = self.ser.read().decode(encoding='ascii')
                    try:
                        gengxinlabel=0
                        gengxinlabel2=0
                        s = str(ch)
                        if s == 'a':
                            s = '\n' + '现有温度：'
                            all = all + ','
                            label1=1
                        elif s=='e':
                            s = '\n' + 'PWM占空比：'
                            all = all + ','
                            label2=1
                        else:
                            all = all + s
                            if label1 == 1 :
                                label1 = 2
                                tennum = int (s)
                            elif label1 == 2 :
                                label1 = 0
                                onenum = int (s)
                                nowtemp = 10 * tennum + onenum
                                tempt [i] = nowtemp
                                print (tempt)
                                self.canvas.create_line(4*i, -10 * tempt[i] + 400, 4*i+4 , -10*tempt[i] + 400, fill='red',tags='o')
                                i = i + 1
                                if i == 100:
                                    i = 0
                                    self.canvas.delete('o')
                                if nowtemp != lasttemp:
                                    print(lasttemp)
                                    lasttemp = nowtemp
                                    gengxinlabel=1
                                    #self.OutputText.insert(tk.END, str1)
                                    str1 = '当前温度：' + str(nowtemp)
                                    print(str1)  


                            elif label2 == 1 :
                                label2 = 2
                                twmtennum = int (s)
                            elif label2 == 2 :
                                label2 = 0
                                twmonenum = int (s)
                                nowpwm = 10 * twmtennum + twmonenum
                                #print(nowpwm)
                                if nowpwm != lastpwm:
                                    print(lastpwm)
                                    lastpwm = nowpwm
                                    gengxinlabel2=1
                                    #self.OutputText.insert(tk.END, str1)
                                    str2 = '当前pwm：' + str(nowpwm) + '\n'
                                    print(str2)       
                        # print(all)
                        data = all.split(',')
                        #print(data)
                        #self.OutputText.insert(tk.END, s)
                        if gengxinlabel==1:
                            self.OutputText.insert(tk.END, str1)
                            self.OutputText1.delete('1.0', 'end')
                            self.OutputText1.insert(tk.END, str1)
                            self.OutputText1.insert(tk.END, str2)
                            gengxinlabe=0
                        # self.OutputText1.insert(tk.END, s)
                        if gengxinlabel2==1:
                            #self.OutputText.delete(0, 'end')
                            self.OutputText.insert(tk.END, str2)
                            self.OutputText1.delete('1.0', 'end')
                            self.OutputText1.insert(tk.END, str1)
                            self.OutputText1.insert(tk.END, str2)
                            gengxinlabe2=0
                    except:
                        s = "geshierror"
                        self.OutputText.insert(tk.END, s)
                except:
                    infromStr = "Something wrong in receiving."
                    InformWindow(infromStr)
                    self.ser.close()  # close the serial when catch exception
                    self.buttonSS["text"] = "开始通信"
                    self.uartState = False
mainGUI()